{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "e0deea1ab1db2a19",
   "metadata": {},
   "source": [
    "# AgentOps Langchain Agent Implementation\n",
    "\n",
    "Using AgentOps monitoring with Langchain is simple. We've created a LangchainCallbackHandler that will do all of the heavy lifting!\n",
    "\n",
    "First let's install the required packages"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "8e3d38adc7861277",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2024-08-08T00:29:29.288644Z",
     "start_time": "2024-08-08T00:29:29.026314Z"
    }
   },
   "outputs": [],
   "source": [
    "%pip install langchain\n",
    "%pip install langchain_openai\n",
    "%pip install agentops\n",
    "%pip install python-dotenv"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "effc8ee7453a6c3",
   "metadata": {},
   "source": [
    "Then import them"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "d344305baa26d651",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2024-08-08T00:29:30.052348Z",
     "start_time": "2024-08-08T00:29:29.289841Z"
    },
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "import os\n",
    "from langchain_openai import ChatOpenAI\n",
    "from langchain.agents import tool, AgentExecutor, create_openai_tools_agent\n",
    "from dotenv import load_dotenv\n",
    "from langchain_core.prompts import ChatPromptTemplate"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "3584d84a441169b0",
   "metadata": {
    "collapsed": false
   },
   "source": [
    "The only difference with using AgentOps is that we'll also import this special Callback Handler"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "256f01cac66d7d90",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2024-08-08T00:29:30.058535Z",
     "start_time": "2024-08-08T00:29:30.054497Z"
    },
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "from agentops.integration.callbacks.langchain import (\n",
    "    LangchainCallbackHandler as AgentOpsLangchainCallbackHandler,\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "afab0f7bbd847916",
   "metadata": {
    "collapsed": false
   },
   "source": [
    "Next, we'll set our API keys. There are several ways to do this, the code below is just the most foolproof way for the purposes of this notebook. It accounts for both users who use environment variables and those who just want to set the API Key here in this notebook.\n",
    "\n",
    "[Get an AgentOps API key](https://agentops.ai/settings/projects)\n",
    "\n",
    "1. Create an environment variable in a .env file or other method. By default, the AgentOps `init()` function will look for an environment variable named `AGENTOPS_API_KEY`. Or...\n",
    "\n",
    "2. Replace `<your_agentops_key>` below and pass in the optional `api_key` parameter to the AgentOps `init(api_key=...)` function. Remember not to commit your API key to a public repo!"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "3f9189f4d13ebd07",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2024-08-08T00:29:30.072366Z",
     "start_time": "2024-08-08T00:29:30.063997Z"
    },
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "load_dotenv()\n",
    "os.environ[\"AGENTOPS_API_KEY\"] = os.getenv(\"AGENTOPS_API_KEY\", \"your_api_key_here\")\n",
    "os.environ[\"OPENAI_API_KEY\"] = os.getenv(\"OPENAI_API_KEY\", \"your_openai_api_key_here\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "6f5a9ab030c636c6",
   "metadata": {
    "collapsed": false
   },
   "source": [
    "This is where AgentOps comes into play. Before creating our LLM instance via Langchain, first we'll create an instance of the AO LangchainCallbackHandler. After the handler is initialized, a session will be recorded automatically.\n",
    "\n",
    "Pass in your API key, and optionally any tags to describe this session for easier lookup in the AO dashboard.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "7d4accd2f68404fb",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2024-08-08T00:29:31.018329Z",
     "start_time": "2024-08-08T00:29:30.074528Z"
    },
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "agentops_handler = AgentOpsLangchainCallbackHandler(tags=[\"Langchain Example\", \"agentops-example\"])\n",
    "\n",
    "llm = ChatOpenAI(callbacks=[agentops_handler], model=\"gpt-3.5-turbo\")\n",
    "\n",
    "# You must pass in a callback handler to record your agent\n",
    "llm.callbacks = [agentops_handler]\n",
    "\n",
    "prompt = ChatPromptTemplate.from_messages(\n",
    "    [\n",
    "        (\"system\", \"You are a helpful assistant. Respond only in Spanish.\"),\n",
    "        (\"human\", \"{input}\"),\n",
    "        # Placeholders fill up a **list** of messages\n",
    "        (\"placeholder\", \"{agent_scratchpad}\"),\n",
    "        # (\"tool_names\", \"find_movie\")\n",
    "    ]\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "f7362d89b6a7af4c",
   "metadata": {
    "collapsed": false
   },
   "source": [
    "Agents generally use tools. Let's define a simple tool here. Tool usage is also recorded."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "4a28f85842129016",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2024-08-08T00:29:31.071133Z",
     "start_time": "2024-08-08T00:29:31.022304Z"
    },
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "@tool\n",
    "def find_movie(genre: str) -> str:\n",
    "    \"\"\"Find available movies\"\"\"\n",
    "    if genre == \"drama\":\n",
    "        return \"Dune 2\"\n",
    "    else:\n",
    "        return \"Pineapple Express\"\n",
    "\n",
    "\n",
    "tools = [find_movie]"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "186984add993f839",
   "metadata": {
    "collapsed": false
   },
   "source": [
    "For each tool, you need to also add the callback handler"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "afe9113b61c67e80",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2024-08-08T00:29:31.073655Z",
     "start_time": "2024-08-08T00:29:31.071945Z"
    },
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "for t in tools:\n",
    "    t.callbacks = [agentops_handler]"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "6dd5f322d26f692",
   "metadata": {},
   "source": [
    "Add the tools to our LLM"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "e469ab337023053e",
   "metadata": {},
   "outputs": [],
   "source": [
    "llm_with_tools = llm.bind_tools([find_movie])"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "88b96e62db542900",
   "metadata": {
    "collapsed": false
   },
   "source": [
    "Finally, let's create our agent! Pass in the callback handler to the agent, and all the actions will be recorded in the AO Dashboard"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "d45ff1b7a3843191",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2024-08-08T00:29:31.127744Z",
     "start_time": "2024-08-08T00:29:31.124945Z"
    }
   },
   "outputs": [],
   "source": [
    "agent = create_openai_tools_agent(llm, tools, prompt)\n",
    "agent_executor = AgentExecutor(agent=agent, tools=tools)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "bb90bf54b5a42a63",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2024-08-08T00:29:32.666768Z",
     "start_time": "2024-08-08T00:29:31.128749Z"
    }
   },
   "outputs": [],
   "source": [
    "agent_executor.invoke({\"input\": \"What comedies are playing?\"}, config={\"callback\": [agentops_handler]})"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "fb276a2e-f1c3-4f0f-8818-b7730e9d3ff7",
   "metadata": {
    "collapsed": false
   },
   "source": [
    "## Check your session\n",
    "Finally, check your run on [AgentOps](https://app.agentops.ai). You will see a session recorded with the LLM calls and tool usage."
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "agentops (3.11.11)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.11.11"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
